<template>
   <div class="add-subjects">
    <el-dialog :title="`${currSubject.id?'修改':'新增'}学科`" :visible.sync="show" width="400px">

      <el-form :model="formModel" :rules="rules" ref="formModel" label-width="88px">
        <el-form-item label="学科名称" prop="subjectName" size="small">
          <el-input v-model="formModel.subjectName" placeholder="请输入学科名称"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="formModel.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            >
          </el-switch>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px;margin-top: 42px;">
          <el-button  @click="cancle('formModel')">取消</el-button>
          <el-button type="primary" @click="submitForm('formModel')">确定</el-button>
        </el-form-item>
      </el-form>
      
    </el-dialog>  
   </div>
</template>

<script>
import {add, update} from '@/api/hmmm/subjects'
export default {
   name: 'SubjectsAdd',
   props: {
    currSubject: {
      default: () => {},
      type: Object
     }
   },
   data() {
     return {
      show: false,
      formModel: {
        id: null,
        subjectName:'',
        isFrontDisplay: 1,
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],  
        isFrontDisplay: [
          { type: 'number', message: '请选择是否显示', tirgger: 'blur' }
        ]
      },

      
     }
   },
   methods: {
    open () {
      this.show = true
      console.log(this.currSubject);
      if (this.currSubject.id) {
        const { id, subjectName, isFrontDisplay } = this.currSubject
        this.formModel = { id, subjectName, isFrontDisplay }
      } else {
        this.formModel = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
    },
    submitForm(formModel) {
      this.$refs[formModel].validate(async valid => {
        if (valid) {
          if(!this.currSubject.id) {
            await add(this.formModel)

          } else {
            this.formModel.id = this.currSubject.id
            await update(this.formModel)
          }

          this.show = false
          this.$message.success('修改成功');
          this.$refs[formModel].resetFields();
          this.$emit('updateList')
        } else {
          this.$message.error('修改失败，请稍后重试!!!');
          return false;
        }
      });
    },
    cancle(formModel) {
      this.show = false
      this.$message.success('取消成功');
      this.$refs[formModel].resetFields();
    }
   }
}
</script>

<style lang='less' scoped>
</style>

